//
//  MapNavigationViewController.m
//  homeland
//
//  Created by rain on 14-10-14.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//

#import "MapNavigationViewController.h"
#import "RouteNavigationViewController.h"
#import "MapTransitRouteListController.h"

#import "TMapView.h"
#import "TPolyline.h"
@class TAnnotation;
@interface MapNavigationViewController ()<TMapViewDelegate,MapTransitRouteListDelegate>
@property (nonatomic, strong) IBOutlet UILabel *titleLabel;
@property (nonatomic, strong) IBOutlet UILabel *subTitleLabel;
@property (nonatomic, strong) IBOutlet UIView *infoView;
@property (nonatomic, strong) IBOutlet TMapView *mapView;
@property (nonatomic, strong) MapTransitRouteListController *listController;
@property (nonatomic, strong) NSMutableArray *arrAnnotation;
@property (nonatomic, strong) TTransitRoute *transitRoute;
@end

@implementation MapNavigationViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)backMethod
{
    [self removeAnnotation];
    [self removeOverlays];
    self.annotation = nil;
    self.location = nil;
    self.mapView.delegate = nil;
    self.mapView = nil;
    self.transitRoute.delegate = nil;
    self.transitRoute = nil;
    
    [self.navigationController popViewControllerAnimated:YES];

}




- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"路线详情";
    
    
    UIButton *busBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image = [UIImage imageNamed:@"route_car"];
    [busBtn setImage:image forState:UIControlStateNormal];
    busBtn.frame = CGRectMake(20, 0, image.size.width/3, image.size.height/2);
    [busBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [busBtn addTarget:self action:@selector(routeNavigation) forControlEvents:UIControlEventTouchUpInside];
//    busBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
    
    UIBarButtonItem* bus = [[UIBarButtonItem alloc] initWithCustomView:busBtn];
    
    UIButton *routeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    image = [UIImage imageNamed:@"route_bus"];
    [routeBtn setImage:image forState:UIControlStateNormal];
    routeBtn.frame = CGRectMake(20, 0, image.size.width/3, image.size.height/2);
    [routeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [routeBtn addTarget:self action:@selector(routeBusList) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* route = [[UIBarButtonItem alloc] initWithCustomView:routeBtn];

    self.navigationItem.rightBarButtonItems = @[bus,route];

    
    self.mapView.delegate = self;
    self.mapView.mapScale = 12;
    self.mapView.ShowPosition = YES;
    // 当前跟踪模式,跟踪状态
    self.mapView.UserTrackMode = TUserTrackingModeNone;
    
    self.titleLabel.text = self.annotation.title;
    self.subTitleLabel.text = self.annotation.title;
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:self.location completionHandler:^(NSArray *placemark,NSError *error)
     {
         CLPlacemark *mark = [placemark objectAtIndex:0];
         self.titleLabel.text = [NSString stringWithFormat:@"%@%@附近",mark.subLocality,mark.thoroughfare];
     } ];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.infoView setFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 45)];
}

- (void)mapView:(TMapView *)mapView didUpdateUserLocation:(TUserLocation *)userLocation;
{
    
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //    self._mapView.mapBound = [self.view bounds]
    [self.mapView StartGetPosition];
    
    [self.mapView addAnnotation:self.annotation];
    [self.mapView selectAnnotation:self.annotation animated:YES];
    [self.mapView setCenterCoordinate:self.location.coordinate animated:NO];
    self.mapView.ShowPosition = YES;
    [self.mapView setFrame:CGRectMake(0, 45 , CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - 45)];
}

#pragma mark 地图地位
- (IBAction)locadiong:(id)sender
{
    [self.mapView StartGetPosition];
}

#pragma mark 缩小地图
- (IBAction)zoomIn:(id)sender
{
    [self.mapView MapScaleSub];
}

#pragma mark 放大地图
- (IBAction)zoomOut:(id)sender
{
    [self.mapView MapScaleAdd];
}

#pragma 自航导航
- (void)routeNavigation
{
    RouteNavigationViewController *vc = [RouteNavigationViewController new];
    vc.location = self.location.coordinate;
    vc.annotation = self.annotation;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma 公交路线
- (void)routeBusList
{
    if (self.transitRoute == nil ) {
        self.transitRoute = [[TTransitRoute alloc] init];
        self.transitRoute.delegate = self;
    }
    TTransitRouteType transitRouteType = pow(2, 0);
    [self.transitRoute startRoute:self.location.coordinate end:self.annotation.coordinate type:transitRouteType];
}


// 清空标注
- (void)removeAnnotation {
    int iSize = [self.arrAnnotation count];
    if (iSize) {
        for (int i = iSize - 1; i >= 0; --i) {
            id item = [self.arrAnnotation objectAtIndex:i];
            [self.mapView removeAnnotation:item];
        }
    }
    [self.arrAnnotation removeAllObjects];
}

- (void)removeOverlays {
    int i = 0;
    NSArray *arrvo = [self.mapView overlays];
    if (arrvo.count) {
        for (; i < arrvo.count; i++) {
            [self.mapView removeOverlay:[arrvo objectAtIndex:i]];
        }
        [self.mapView setNeedsDisplay];
    }
}
//

- (TOverlayView *)mapView:(TMapView *)mapView viewForOverlay:(id <TOverlay>)overlay {
    TPolylineView *lineview = [[TPolylineView alloc] initWithPolyline:overlay mapView:mapView];
    lineview.lineWidth = 4;
    lineview.strokeColor = [UIColor redColor];
    return lineview;
}

// 用户实现创建一个动态标注视图
- (TAnnotationView *)mapView:(TMapView *)mapView viewForAnnotation:(id <TAnnotation>)annotation {
    if ([self.arrAnnotation indexOfObject:annotation] != NSNotFound) {
        static NSString *CellIdentifier = @"transitroute";
        TAnnotationView *annotationView = [[TAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:CellIdentifier];
        annotationView.image = [UIImage imageNamed:@"icon_routelable_turn"];
        annotationView.selectImage = [UIImage imageNamed:@"icon_routelable_turn"];
        if (annotation == self.annotation) {
            annotationView.image = [UIImage imageNamed:@"route_bus_result_end"];
            annotationView.selectImage = [UIImage imageNamed:@"route_bus_result_end"];

        }
 
        annotationView.canShowCallout = TRUE;
        CGPoint ptoffset = CGPointMake(annotationView.image.size.width / 2, 0);
        annotationView.calloutOffset = ptoffset;
        return annotationView;
    }
    
    return nil;
}

- (void)mapView:(TMapView *)mapView didSelectAnnotationView:(TAnnotationView *)view {
    NSArray *arrSelect = mapView.selectedAnnotations;
    for (int i = 0; i < arrSelect.count; i++) {
        id <TAnnotation> ann = [arrSelect objectAtIndex:i];
        if (ann != view.annotation) {
            [mapView deselectAnnotation:ann animated:YES];
        }
    }
}


#pragma mark -
#pragma mark ---------TTransitRouteDelegate---------
// 公交规划结果回调函数
- (void)transitRouteResult:(TTransitRouteResult *)pTransitResult
                 errorCode:(int)iErrorCode {
    if (iErrorCode != 0) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"公交规划失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alertView show];

        return;
    }
    
    if ([pTransitResult.result count] > 0) {
        TTransitRouteSingleTypeResult *pSingleResult = [pTransitResult.result objectAtIndex:0];
        NSInteger iLineCount = [pSingleResult.line count];
        NSString *strMsg = [NSString stringWithFormat:@"TransitRouteResult 方案数%d", iLineCount];
//        _info.text = strMsg;
        
        
        // 跳转到结果列表
        if (self.listController == nil) {
            self.listController = [MapTransitRouteListController new];
            self.listController._delegate = self;
            //        listController._mapView = _mapView;
        }
        self.listController.pTransitRouteResult = pTransitResult;
        
        [[self navigationController] pushViewController:self.listController animated:YES];
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"当前规划类型无结果。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alertView show];
    }
}

#pragma mark -
#pragma mark ---------MapTransitRouteListDelegate---------
- (void)MapTransitRouteListController:(id)sender selectLine:(TTransitRouteLine *)pLine AtIndex:(int)iIndex {
    
    // 清空标注
    [self removeAnnotation];
    [self removeOverlays];
    
    // 获取起终点坐标
    CLLocationCoordinate2D startPoi = {0};
    CLLocationCoordinate2D endPoi = {0};
    startPoi.longitude = self.location.coordinate.longitude;
    startPoi.latitude = self.location.coordinate.latitude;
    endPoi.longitude = self.annotation.coordinate.longitude;
    endPoi.latitude = self.annotation.coordinate.latitude;
    
    // 添加地图标注
    int iPos = 0;
    int iSize = [pLine.segment count];
    if (iSize) {
        TTransitRouteSegment *pSegment = nil;
        TTransitRouteSegmentLine *pSegmentLine = nil;
        TPolyline *line = nil;
        MyAnnotation *temp = nil;
        self.arrAnnotation = [[NSMutableArray alloc] initWithCapacity:iSize + 2];
        // 起点
        temp = [[MyAnnotation alloc] init];
        temp.title = @"起点";
        temp.coordinate = startPoi;
        [self.arrAnnotation addObject:temp];
        
        // 站点
        NSString *strText = nil;
        for (; iPos < iSize; iPos++) {
            pSegment = [pLine.segment objectAtIndex:iPos];
            switch (pSegment.type) {
                case TRANSIT_SEGMENT_TYPE_WALK:
                    strText = [self.listController getWalkDescriptionWithIndex:iPos routeLine:pLine];
                    break;
                case TRANSIT_SEGMENT_TYPE_BUS:
                case TRANSIT_SEGMENT_TYPE_SUBWAY:
                    strText = [self.listController getBusDescriptionWithIndex:iPos routeLine:pLine];
                    break;
                case TRANSIT_SEGMENT_TYPE_SUBWAYTRANSFER:
                    strText = [self.listController getSubwayTransferDescriptionWithIndex:iPos routeLine:pLine];
                    break;
                default:
                    break;
            }
            temp = [[MyAnnotation alloc] init];
            temp.title = [NSString stringWithFormat:@"%d.%@", iPos + 1, strText];
            //    temp.subtitle = [NSString stringWithFormat:@"(id:%@)", record.strId];
            temp.coordinate = pSegment.start.point;
            [self.arrAnnotation addObject:temp];
            
            // 绘制路线
            pSegmentLine = [pSegment.segmentLine objectAtIndex:0];
            if (pSegmentLine.pointCount) {
                line = [TPolyline polylineWithCoordinates:pSegmentLine.shapePoints count:pSegmentLine.pointCount];
                [self.mapView addOverlay:line];
                [self.mapView setNeedsDisplay];
            }
        }
        // 终点
        temp = [[MyAnnotation alloc] init];
        temp.title = @"终点";
        temp.coordinate = endPoi;
        [self.arrAnnotation addObject:temp];
        
        [self.mapView addAnnotations:self.arrAnnotation];
        id item = [self.arrAnnotation objectAtIndex:iIndex + 1];
        [self.mapView selectAnnotation:item animated:YES];
        [self.mapView setRegion:pLine.region];
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
